//
//  LocalFileManager.m
//  YuanXinKit
//
//  Created by 晏德智 on 2016/11/4.
//  Copyright © 2016年 晏德智. All rights reserved.
//

#import "LocalFileManager.h"
#import "SystemFileManager.h"

@implementation LocalFileManager

- (NSDictionary<NSString *, NSString *> *)constantsToExport {
    return @{STORAGE_BACKED_UP: [[SystemFileManager baseDirForStorage:STORAGE_BACKED_UP] path],
             STORAGE_IMPORTANT: [[SystemFileManager baseDirForStorage:STORAGE_IMPORTANT] path],
             STORAGE_AUXILIARY: [[SystemFileManager baseDirForStorage:STORAGE_AUXILIARY] path],
             STORAGE_TEMPORARY: [[SystemFileManager baseDirForStorage:STORAGE_TEMPORARY] path]};
}


RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(writeToFile:(NSString*)relativePath content:(NSString*)content inStorage:(NSString*)storage resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
    [SystemFileManager writeToFile:relativePath content:content inStorage:storage];
    resolve([NSNumber numberWithBool:YES]);
}


RCT_EXPORT_METHOD(readFile:(NSString*)relativePath inStorage:(NSString*)storage resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
    NSError *error;
    NSString *content = [SystemFileManager readFile:relativePath inStorage:storage error:&error];
    if (error != nil) {
        reject(@"RNFileSystemError", [error localizedDescription], error);
    } else {
        resolve(content);
    }
}

RCT_EXPORT_METHOD(fileExists:(NSString*)relativePath inStorage:(NSString*)storage resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
    BOOL fileExists = [SystemFileManager fileExists:relativePath inStorage:storage];
    resolve([NSNumber numberWithBool:fileExists]);
}

RCT_EXPORT_METHOD(directoryExists:(NSString*)relativePath inStorage:(NSString*)storage resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
    BOOL folderExists = [SystemFileManager directoryExists:relativePath inStorage:storage];
    resolve([NSNumber numberWithBool:folderExists]);
}

RCT_EXPORT_METHOD(delete:(NSString*)relativePath inStorage:(NSString*)storage resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
    BOOL deleted = [SystemFileManager deleteFileOrDirectory:relativePath inStorage:storage];
    resolve([NSNumber numberWithBool:deleted]);
}

@end
